from django.shortcuts import render
from rest_framework.views import APIView

# Create your views here.


from django.shortcuts import render

# Create your views here.
from rest_framework import status
from rest_framework.decorators import action
from rest_framework.generics import CreateAPIView
from rest_framework.mixins import CreateModelMixin, UpdateModelMixin
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import GenericViewSet
from rest_framework_jwt.serializers import JSONWebTokenSerializer
from rest_framework_jwt.views import JSONWebTokenAPIView

from users.models import User


from users.serializers import CreateUserSerializer, AddressSerializer, AddressTitleSerializer


#用户是否存在

class UsernameCountView(APIView):
    def get(self, request, username):
        """
        获取用户名数量:
        1. 查询数据库获取用户名数量
        2. 返回应答
        """
        # 1. 查询数据库获取用户名数量
        count = User.objects.filter(username=username).count()

        # 2. 返回应答
        response_data = {
            'username': username,
            'count': count
        }
        return Response(response_data)

#手机号是否存在
# GET mobile/(?P<mobile>1[3-9]\d{9})/count/
class MobileCountView(APIView):
    def get(self, request, mobile):
        """
        获取手机号数量:
        1. 查询数据库获取手机号数量
        2. 返回应答
        """
        # 1. 查询数据库获取手机号数量
        count = User.objects.filter(mobile=mobile).count()

        # 2. 返回应答
        response_data = {
            'mobile': mobile,
            'count': count
        }
        return Response(response_data)

# POST /users/
#注册
class UserView(CreateAPIView):
    # 指定视图所使用的序列化器类
    serializer_class = CreateUserSerializer


class ObtainJSONWebToken(JSONWebTokenAPIView):

    serializer_class = JSONWebTokenSerializer


#地址管理
class AddressViewSet(CreateModelMixin, UpdateModelMixin, GenericViewSet):
    permission_classes = [IsAuthenticated]
    serializer_class = AddressSerializer

    def get_queryset(self):
        '''返回视图所使用的查询集'''
        return self.request.user.addresses.filter(is_deleted=False)

    #post/addresses/
    def create(self, request, *args, **kwargs):
        '''
        request.user:登陆用户对象
        新增地址数据的保存
        1.判断用户的地址数据是否超过上限
        2.获取参数并进行校验(参数完整性,手机号格式)
        3.保存新增地址的数据
        4.将新增地址的数据序列化并返回
        '''
        #判断用户地址是否超过上限
        count = request.user.addresses.filter(is_deleted=False).count()
        if count>= 20:
            return Response({'message':'地址数量超过最大上限'},status=status.HTTP_403_FORBIDDEN)

        #调用CreateModelMixin中的create
        return super().create(request)

    #get/addresses/
    def list(self,request):
        '''
        获取登陆用户的地址信息
        1.获取登陆用户的地址的数据
        2.将地址的数据序列化
        3.返回响应

        '''
        #1.获取登陆用户的地址数据
        addresses=self.get_queryset()
        #2.将地址数据序列化
        serializer = self.get_serializer(addresses, many=True)
        #3.返回响应
        response_data={
            'user_id':request.user.id,
            'default_address_id':request.user.default_address_id,
            'limit':20,
            'addresses':serializer.data

        }
        return Response(response_data)

        # DELETE /address/(?P<pk>\d+)/

    def destroy(self, request, pk):
        """
        删除指定的地址数据:
        1. 根据pk获取指定的地址数据
        2. 将地址数据进行逻辑删除
        3. 返回应答，status=204
        """
        # 1. 根据pk获取指定的地址数据
        address = self.get_object()

        # 2. 将地址数据进行逻辑删除
        address.is_deleted = True
        address.save()

        # 3. 返回应答，status=204
        return Response(status=status.HTTP_204_NO_CONTENT)

        # PUT /addresses/(?P<pk>\d+)/status/

    @action(methods=['put'], detail=True)
    def status(self, request, pk):
        """
        设置默认地址:
        1. 根据pk获取对应地址数据
        2. 将此地址设置为用户的默认地址
        3. 返回应答
        """
        # 1. 根据pk获取对应地址数据
        address = self.get_object()

        # 2. 将此地址设置为用户的默认地址
        # request.user.default_address = address
        request.user.default_address_id = address.id
        request.user.save()

        # 3. 返回应答
        return Response({'message': 'OK'})
    #
    # # PUT /addresses/(?P<pk>\d+)/title/
    # @action(methods=['put'], detail=True)
    # def title(self, request, pk):
    #     """
    #     修改指定地址的标题:
    #     1. 根据pk获取指定的地址数据
    #     2. 获取title并校验
    #     3. 修改地址的title标题
    #     4. 返回应答
    #     """
    #     # 1. 根据pk获取指定的地址数据
    #     address = self.get_object()
    #
    #     # 2. 获取title并校验
    #     serializer = AddressTitleSerializer(address, data=request.data)
    #     serializer.is_valid(raise_exception=True)
    #
    #     # 3. 修改地址的title标题(update)
    #     serializer.save()
    #
    #     # 4. 返回应答
    #     return Response(serializer.data)














